#!/usr/bin/python
# -*- coding:utf-8 -*-
from lib.utils.display import Display
from lib.data.AnsibleData import Format
from lib.db.mysqlObj import cmdb_hosts as table

display = Display()


class Load(object):
    def __init__(self):
        display.info('Data Format Started.')
        self.dicFormalData = Format().to_dic_multiple()
        # print self.dicFormalData
        self.dicSum = dict(
            sum_total=self.dicFormalData['counts'],
            sum_success=0,
            sum_failed=0,
            sum_inserted=0,
            sum_updated=0,
            sum_process=0,
        )
        display.info('Data Format Finished.')

    def RunHosts(self):
        for key, value in self.dicFormalData['data'].items():
            counts = table().Query(value)
            if counts != 0:
                status = table().Update(value)
                if status == 'success':
                    self.dicSum['sum_success'] += 1
                    self.dicSum['sum_updated'] += 1
                else:
                    self.dicSum['sum_failed'] += 1
                    display.error(
                     'Load Ansible Data to MySQL - error : %s' % value['IP']
                    )
            else:
                status = table().Insert(value)
                if status == 'success':
                    self.dicSum['sum_success'] += 1
                    self.dicSum['sum_inserted'] += 1
                else:
                    self.dicSum['sum_failed'] += 1
                    display.error(
                     'Load Ansible Data to MySQL - error : %s' % value['IP']
                    )
            self.dicSum['sum_process'] += 1
            display.info(
              'Load Ansible Data to MySQL(%s/%s) -- %s -- %s' % (
                self.dicSum['sum_process'],
                self.dicSum['sum_total'],
                value['IP'], status
              )
            )
        return self.dicSum

# x=Load()
# print x.RunHosts()
